<!-- admin-dashboard/src/views/Dashboard.vue -->
<template>
  <div class="dashboard">
    <h2>Admin Dashboard</h2>
    <el-tabs v-model="activeTab">
      <el-tab-pane label="Users" name="users">
        <el-table :data="users" style="width: 100%">
          <el-table-column prop="_id" label="ID" />
          <el-table-column prop="username" label="Username" />
          <el-table-column prop="email" label="Email" />
          <el-table-column label="Actions">
            <template #default="{ row }">
              <el-button type="danger" size="small" @click="deleteUser(row._id)">
                Delete
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-tab-pane>
      <el-tab-pane label="Messages" name="messages">
        <el-table :data="messages" style="width: 100%">
          <el-table-column prop="_id" label="ID" />
          <el-table-column prop="from" label="From" />
          <el-table-column prop="to" label="To" />
          <el-table-column prop="content" label="Content" />
          <el-table-column prop="timestamp" label="Time" />
        </el-table>
      </el-tab-pane>
    </el-tabs>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import axios from 'axios';
import { ElMessage } from 'element-plus';

const activeTab = ref('users');
const users = ref([]);
const messages = ref([]);

const fetchUsers = async () => {
  try {
    const res = await axios.get('http://61.184.21.191:3001/api/v1/admin/users', {
      headers: { Authorization: `Bearer ${localStorage.getItem('token')}` }
    });
    users.value = res.data.users;
  } catch (err) {
    ElMessage.error('Failed to fetch users: ' + (err.response?.data?.error || err.message));
  }
};

const fetchMessages = async () => {
  try {
    const res = await axios.get('http://your-server-ip:3000/api/v1/admin/messages', {
      headers: { Authorization: `Bearer ${localStorage.getItem('token')}` }
    });
    messages.value = res.data.messages;
  } catch (err) {
    ElMessage.error('Failed to fetch messages: ' + (err.response?.data?.error || err.message));
  }
};

const deleteUser = async (userId) => {
  try {
    await axios.delete(`http://your-server-ip:3000/api/v1/admin/users/${userId}`, {
      headers: { Authorization: `Bearer ${localStorage.getItem('token')}` }
    });
    ElMessage.success('User deleted');
    fetchUsers();
  } catch (err) {
    ElMessage.error('Failed to delete user: ' + (err.response?.data?.error || err.message));
  }
};

onMounted(() => {
  fetchUsers();
  fetchMessages();
});
</script>

<style scoped>
.dashboard {
  max-width: 1200px;
  margin: 20px auto;
}
</style>